package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import cn.com.kh.KHUtil;
import cn.com.kh.hst.ThreeDesUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTHandLogin
 * @Description:华盛证券 SSO统一校验登录接口 --内部接口
 * @author: cheih
 * @date 2021-07-07 10:28:00
 *
 */

public class aipHSTHandLogin implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(aipHSTHandLogin.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {

			long startTime = System.currentTimeMillis();
			String reJson = null;
			long endTime = 0;

			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());
			def loginname = GetJV(inObject, "loginname");//账号
			def password="";//密码
			def remoteAddr="";//坐席ip
			def countresult =eliteBean.chaxun_sql("select  s.Stringfield3 as password,b.CLIENTIP as remoteAddr from  webloginlist b left join staff s on s.STAFF_ID=b.STAFF_ID where   s.Stringfield1 is not null and b.CLIENTIP is not null and loginname='" + loginname + "'", "dataSource");
			if(countresult.size()>0) {
				password = countresult.get(0).get("password");
				remoteAddr = countresult.get(0).get("remoteAddr");
			}else {
				log.debug("loginname不存在");
				reJson = "{\"result\":\"-1\",\"message\":\"登录账号SSO验证异常\"}";
				return reJson;
			}

			log.debug("解析信息-" + "loginname: " + loginname+ "password: " + password+ "remoteAddr: " + remoteAddr);
						
			//鉴权变量
			String appid = getProperty.get("appid");
			String appsecret = getProperty.get("appsecret");

			//sign加密前后
			String signfront = "";
			String signafter = "";

			//操作员密码，3DES加密传输
			String passwordEncrypted=ThreeDesUtil.encode(appsecret, password);
			String passwordEncrypted1= URLEncoder.encode(passwordEncrypted, "utf-8");
			log.debug("解析信息-" + "passwordEncrypted1: " + passwordEncrypted1);			
			
			String sign_time=Instant.now().getEpochSecond();
			log.debug("解析信息-" + "passwordEncrypted: " + passwordEncrypted+ "sign_time: " + sign_time);


			HashMap<String, String> paramHashMap = new HashMap<String, String>() {
						{
							put("account", loginname);
							put("passwordEncrypted", passwordEncrypted);
							put("remoteAddr", remoteAddr);
							put("sign_time", sign_time);
						}
					};
					
			HashMap<String, String> paramHashMap1 = new HashMap<String, String>() {
					{
							put("account", loginname);
							put("passwordEncrypted", passwordEncrypted1);
							put("remoteAddr", remoteAddr);
							put("sign_time", sign_time);
					}
				};

			log.debug("paramHashMap：" + paramHashMap);
			//自然排序 升序参数
			signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
			log.debug("sign加密MD5前：" + signfront);
			signafter = Util.getMD5Str(signfront);
			log.debug("sign加密MD5后：" + signafter);

			//拼接接口入参
			paramHashMap1.put("client_key", appid);
			paramHashMap1.put("sign", signafter);

			String injson=ThreeDesUtil.SplicingMap(paramHashMap1,"&");
			log.debug("injson:" + injson);

			outData = Loginin(eliteBean, injson,password,dataSourceID);

		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
		}
		log.debug("处理完成返回结果:" + outData);

		return outData;
	}

	//Loginin
	public static String Loginin(EliteBean eliteBean , String injson,String password, String dataSourceID) {

		long startTime = System.currentTimeMillis();
		log.debug("处理开始时间:" + startTime);

		long endTime = System.currentTimeMillis();

		String reJson = null;
		try {

			String doURL = getProperty.get("HSTURL");
			doURL = doURL+"/passport/admin/login";
			log.debug("doURL:" + doURL);

			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/x-www-form-urlencoded");
			def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
			log.debug("getResult:" + getResult);

			//解析SSO返回信息
			JSONObject jsonObject = new JSONObject(getResult);
			String code = GetJV(jsonObject, "code");
			String result = GetJV(jsonObject, "result");

			JSONObject dataObject;
			log.debug("code:" + code);
			if(code == "00000") {
				dataObject = new JSONObject(result);
				log.debug("dataObject:" + dataObject);
				String loginname = GetJV(dataObject, "account");
				String userName = GetJV(dataObject, "userName");
				String token = GetJV(dataObject, "token");

				String[] data1=new String[1];
				//data1[0] = "Update Staff Set Staffname = '" + userName + "', Pwdmodify = Now(), Stringfield1 = '" + token + "',stringfield2=NOW() Where Loginname = '" + loginname + "'";
				data1[0] = "Update Staff Set Pwdmodify = Now(), Stringfield1 = '" + token + "',stringfield2=NOW() Where Loginname = '" + loginname + "'";
				log.debug("当前登陆人员已经存在CC系统账号执行更新SQL:" + data1.toString());


				int[] dataresult1 = eliteBean.updateBatch(data1, "dataSource");
				log.debug("CC系统登录信息表STAFF操作SQL结果:" + dataresult1.toString());


				//返回认证信息成功
				reJson = "{\"result\":\"1\",\"message\":\"token更新成功\",\"token\":\"" + token + "\"}";
			}else {
				String msg = GetJV(jsonObject, "msg");
				reJson = "{\"result\":\"-1\",\"message\":\"token验证失败(" + msg + ")\"}";
			}

		} catch (JSONException e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			reJson = "{\"result\":\"-1\",\"message\":\"登录账号SSO验证异常\"}";
		}

		return reJson;
	}


	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}


	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}
		log.debug(reFlag);
		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}

}
